import {defineEventHandler, readBody } from 'h3'
import JSZip from 'jszip'

export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  const images: string[] = Array.isArray(body && body.images) ? body.images : []
  const name = (body && body.name) ? String(body.name) : 'images'

  if (!images.length) {
    return { error: 'no images provided' }
  }

  // limit to avoid abuse
  const max = 50
  const list = images.slice(0, max)

  const zip = new JSZip()

  for (let i = 0; i < list.length; i++) {
    const u = list[i]
    try {
      // fetch as arrayBuffer
      const arr = await $fetch(u, { method: 'GET', responseType: 'arrayBuffer' })
      const buf = Buffer.from(arr as ArrayBuffer)
      // derive filename
      let fname = 'image-' + (i + 1)
      try {
        const urlObj = new URL(u)
        const path = urlObj.pathname.split('/').filter(Boolean).pop() || ''
        if (path) fname = path
      } catch (e) {}
      zip.file(fname, buf)
    } catch (e) {
      // skip failed fetches
    }
  }

  const content = await zip.generateAsync({ type: 'nodebuffer' })

  // send as attachment
  const res = event.node.res
  res.setHeader('Content-Type', 'application/zip')
  res.setHeader('Content-Disposition', `attachment; filename="${name}.zip"`)
  res.setHeader('Content-Length', String(content.length))
  res.end(content)

  return ''
})
